import axios from 'axios'
import qs from 'qs'
import {
    Message,
    MessageBox
} from 'element-ui'
import store from '@/store'
import {
    getToken
} from '@/utils/auth'

// 创建axios实例
const service = axios.create({
    baseURL: process.env.BASE_API, // api的base_url
    timeout: 500000, // 请求超时时间
    headers: {
        'Content-Type': 'application/json;charset=UTF-8'
    }
})

// request拦截器
service.interceptors.request.use(config => {
    var authStr = getToken()
    if (config.data && config.method == 'get') {
        config.data = qs.stringify(data, { indices: false })
    }
    if (authStr) {
        // config.headers['sessionid'] = 'bnnebf59i8nsjg498hl1qk24a2rmtevk'
        config.headers['Authorization'] = 'token' + authStr // 让每个请求携带自定义token 请根据实际情况自行修改
            //config.headers['token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
        config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    }
    return config
}, error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
})

// respone拦截器
// respone拦截器
service.interceptors.response.use(
    response => {
        /**
         * code为非200是抛错 可结合自己业务进行修改
         */
        const res = response
        if ([200, 201, 202, 203, 204, 205, 206].includes(res.status)) {
            return res.data
        } else if (res.status === 207) {
            Message({
                message: res.data.message,
                type: 'warning',
                duration: 5 * 1000
            })
            return {}
        } else if (res.status === 401) {
            handleAuthFaild()
        } else if (res.code === 400) {
            Message({
                message: res.message,
                type: 'warning',
                duration: 5 * 1000
            })
            return {}
        } else {
            Message({
                message: res.message,
                type: 'error',
                duration: 2 * 1000
            })
            return Promise.reject(res)
        }
    },
    error => {
        console.log('http receive error')
        console.log(error) // for debug
            // debugger
        if (error.response && error.response.status === 401) {
            // debugger
            handleAuthFaild()
        } else if (error.response && error.response.status === 403) {
            Message({
                message: window.vm.$t('message.NoAccess'),
                type: 'error',
                duration: 5 * 1000
            })
            return Promise.reject({
                data: error,
                message: '无权限'
            })
        } else {
            if (!(error.response && error.response.config.responseType === 'arraybuffer')) {
                Message({
                    message: error.response ? error.response.data.message : error.message,
                    type: 'error',
                    duration: 5 * 1000
                })
            }

            return Promise.reject({
                data: error,
                message: error.response ? error.response.data.message : error.message
            })
        }
    }
)

function handleAuthFaild() {
    MessageBox.confirm('你已被登出,请重新登录！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false,
        closeOnPressEscape: false,
        showCancelButton: false,
        showClose: false
    }).then(() => {
        store.dispatch('LogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
        })
    })
}

export default service